package handler

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"time"
	"zk/zg3_zk2/src/pro/global"
	"zk/zg3_zk2/src/pro/internal/models"
	"zk/zg3_zk2/src/pro/internal/params"
)

func Login(c *gin.Context) {
	var err error
	var req params.LoginReq
	var u models.User

	if err = c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err = u.GetUserByMobile(req.Mobile); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "用户信息获取失败！"})
		return
	}
	if u.ID == 0 {
		u.Mobile = req.Mobile
		u.Password = req.Password

		result, _ := global.Rdb.Get(global.Ctx, "sendSms"+req.Mobile).Result()
		if result != req.SmsCode {
			c.JSON(http.StatusNotFound, gin.H{"error": "短信验证码错误！"})
			return
		}

		if err = u.Register(); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "用户注册失败！"})
			return
		}
	}

	if u.Password != req.Password {
		c.JSON(http.StatusNotFound, gin.H{"error": "密码错误！"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    400,
		"message": "用户登录成功",
		"userId":  u.ID,
	})
}

func SendSms(c *gin.Context) {
	var err error
	var req params.SendSmsReq
	code := rand.Intn(9000) + 1000

	if err = c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	//sms, _ := sendSms.SendSms(req.Mobile, strconv.Itoa(code))
	//if *sms.Body.Code != "OK" {
	//	c.JSON(http.StatusInternalServerError, gin.H{"error": *sms.Body.Message})
	//	return
	//}

	global.Rdb.Set(global.Ctx, "sendSms"+req.Mobile, code, time.Minute*5)

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "短信验证码发送成功",
	})
}

func UserInfo(c *gin.Context) {
	var err error
	var req params.UserInfoReq
	var ui models.UserInfo

	if err = c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	key := fmt.Sprintf("userInfo_%d", req.UserId)
	cacheData, _ := global.Rdb.Get(global.Ctx, key).Result()
	if cacheData == "" {
		if err = ui.GetUserInfByUserId(req.UserId); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"code":  404,
				"error": "该用户不存在",
			})
			return
		}

		jsonData, _ := json.Marshal(ui)
		global.Rdb.Set(global.Ctx, key, jsonData, time.Minute*5)

	} else {
		err = json.Unmarshal([]byte(cacheData), &ui)
		if err != nil {
			return
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "用户主页信息展示成功",
		"data":    ui,
	})
}
